<template>
  <div class="upload-wrapper">
    <el-button-group>
      <el-button type="primary" @click="handleUpload">EXCEL上传</el-button>
      <el-button type="primary" @click="massCertified">批量验证</el-button>
    </el-button-group>

    <input class="hidden-input" type="file" ref="uploadInput" @change="changeHandler">
  </div>
</template>

<script>
import xlsx from 'xlsx';

const _SheetJSFT = [
  "xlsx", "xlsb", "xlsm", "xls", "xml", "csv", "txt", "ods", "fods", "uos", "sylk", "dif", "dbf", "prn", "qpw", "123", "wb*", "wq*", "html", "htm"
].map(function (x) { return "." + x; }).join(",");

// const make_cols = refstr => Array(xlsx.utils.decode_range(refstr).e.c + 1)
//   .fill(0)
//   .map((x, i) => ({ name: xlsx.utils.encode_col(i), key: i }));

const genKeys = (query, list) => query
  .map(({ label, key }) => ({ key, index: list.findIndex(e => e === label) }))
  .filter(e => e.index > -1)

const genData = (list, keys) => keys.reduce((pre, current) => {
  pre[current.key] = list[current.index]
  return pre
}, {})


export default {
  props: {
    queryParams: {
      type: Array,
      required: true
    },
    verifyMethod: {
      type: Function,
      required: true,
      default: () => { }
    }
  },
  data () {
    return {
      data: [],
    }
  },
  watch: {
    data (value) {
      const [head, ...rest] = value

      const keys = genKeys(this.queryParams, head)
      const rst = rest.map(item => genData(item, keys))
      this.$emit('update:xlsxData', rst)
    }
  },
  methods: {
    handleUpload (file) {
      const { uploadInput } = this.$refs;
      uploadInput.click()
    },
    changeHandler (e) {
      const { files } = e.target;
      if (files && files[0]) this.handleFile(files[0]);
    },
    handleFile (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        /* Parse data */
        const bstr = e.target.result;
        const wb = xlsx.read(bstr, { type: 'binary' });
        /* Get first worksheet */
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        /* Convert array of arrays */
        const data = xlsx.utils.sheet_to_row_object_array(ws, { header: 1 });
        /* Update state */
        this.data = data;
        // this.cols = make_cols(ws['!ref']);
      };
      reader.readAsBinaryString(file);
    },
    massCertified () {
      console.log('???')
      return this.verifyMethod()
    }
  }
}
</script>

<style>
.hidden-input {
  width: 0;
  height: 0;
}
.upload-wrapper {
  display: inline;
}
</style>
